package com.grace.util.Hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * Hibernate工具类
 */
public class HibernateUtil {

    //SessionFactory是重量级对象,只需要创建一次
    private static SessionFactory sf;

    static {
        //1.创建Configuration实例
        //Configuration cfg = new Configuration();

        //2.读取配置文件及映射文件
        Configuration cfg = new Configuration().configure();

        //3.创建SessionFactory对象
        ServiceRegistry sr = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        sf = cfg.buildSessionFactory(sr);
    }

    /**
     * 获取Session的方法
     */
    public static Session getSession() {
        return sf == null ? null : sf.openSession();
    }

    /**
     * 关闭Session的方法
     */
    public static void close(Session ses) {
        if (ses != null) {
            ses.close();
        }
    }
}
